'''
Created on 2011-06-30

@author: Mikael
'''

import os.path
from Model.GenericNode import GenericNode
from Model.NodeFolder import NodeFolder
from Model.NodeResource import NodeResource
from Model.Resource import ResourceType, Resource
from Model.Entity import Entity
from  xml.dom.minidom import Document, Text
from  xml.dom.minidom  import Element
import xml.dom.minidom
from PyQt4.QtCore import pyqtSignal, QObject, pyqtSlot
from Model.TreeModel import TreeModel


class Project(QObject):
    '''
    A 3dk project
    '''
    mSignalChanged = pyqtSignal(GenericNode)
    
    PROJECT_NODE = "Project"
    PROJECT_NAME_NODE = "Name"
    
    PROJECT_PATH_NODE = "ProjectPath"

    def __init__(self, filePathStr="", name="ProjectName"):
        '''
        Load a project from a given path
        '''
        #if not os.path.exists(filePathStr):
        #    raise Exception("Project filepath not valid: " + filePathStr)
        super(Project, self).__init__()
        self.Initialize(filePathStr, name)
        self.mRootNode = self.GenerateNodes()
        self.mModel = TreeModel(["Project"], [self.mRootNode])
        
        
        
    def Initialize(self, filePath="", name=""):
        self.mFilePath = filePath
        self.mName = name
        
    def addFolder(self, foldername):
        node = NodeFolder(foldername)
        self.mRootNode.addChildNode(node)
        self.mSignalChanged.emit(node)
        
    def addScene(self, sceneName):
        node = NodeResource(Resource(ResourceType.Scene, "/Dossier1/" + sceneName) );
        self.mRootNode.addChildNode(node)
        self.mSignalChanged.emit(node)
        
        
    def reloadFromFile(self, filePath):
        '''
        Reload the project from a file
        '''
        self.propagateUnload()
        self.loadFromFile(filePath)
        self.propagateLoad()
        
     
    def GenerateNodes(self):
        
        rootNode = GenericNode(["Project"])
        
        hardFolder0 = NodeFolder("Folder1")
        rootNode.addChildNode(hardFolder0)
        hardRes1 = NodeResource(Resource(ResourceType.Material, "/Dossier1/Material1") );
        hardRes2 = NodeResource(Resource(ResourceType.Effect, "/Dossier1/Effect1" ) );
        hardFolder0.addChildNode(hardRes1)
        hardFolder0.addChildNode(hardRes2)
        
        hardFolder1 = NodeFolder("Folder2")
        rootNode.addChildNode(hardFolder1)
        hardRes3 = NodeResource(Resource(ResourceType.Texture, "/Dossier2/Texture1" ) );
        hardFolder1.addChildNode(hardRes3)
        hardRes4 = NodeResource(Resource(ResourceType.Scene, "/Dossier2/SceneLight" ) );
        hardFolder1.addChildNode(hardRes4)

        return rootNode;
    
    def propagateUnload(self):
        '''
        Singnal all observers to unload the project
        '''
        
    def propagateLoad(self):
        '''
        Singnal all observers to unload the project
        '''
    
    def getTreeModel(self):
        return self.mModel 
        
    #################################    
    # Load file
    #################################   
    def loadFromFile(self, filePath):
        file = open(filePath, "r")
        self.mFilePath = filePath
        
        xmlDoc = xml.dom.minidom.parse(file);
        self.loadProjectNode(xmlDoc)
        
    def loadProjectNode(self, Document):

        projectNode = Document.childNodes[0];
        
        for Element in projectNode.childNodes:
            if Element.nodeName == self.PROJECT_NAME_NODE:
                self.loadNameNode(Document, Element)
    
    def loadNameNode(self, Document, Element):
        self.mName = self.getNodeText(Element)

        
        
    def getNodeText(self, Element):
        nodelist = Element.childNodes
        rc = []
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
        return ''.join(rc)
                
    
        
        
        
    
    #################################    
    # Save file
    ################################# 
    def saveToFile(self):
        '''
        Save the project to it's file path
        '''
        file = open(self.mFilePath, "w")
        
        xmlDoc = xml.dom.minidom.Document()
        self.saveProjectNode(xmlDoc)
        
        prettyXml = xmlDoc.toprettyxml("\t", "\n")
        print(prettyXml)
        
        file.write(prettyXml)
        file.close()
    
    def saveProjectNode(self, Document=Document()):
        projectNode = Document.createElement(self.PROJECT_NODE)
        Document.appendChild(projectNode)
        
        self.saveNameNode(Document, projectNode)
        #self.savePathNode(Document, projectNode)
        
    def saveNameNode(self, Document, Element):
        nameNode = self.createTextNode(Document, self.PROJECT_NAME_NODE, self.mName)
        Element.appendChild(nameNode)
        
    def savePathNode(self, Document, Element):
        pathNode = self.createTextNode(Document, self.PROJECT_PATH_NODE, self.mFilePath)
        Element.appendChild(pathNode)
        
        
    #################################    
    # UTIL
    #################################
        
    def createTextNode(self, Document, elementName="", text=""):
        elementNode = Document.createElement(elementName)
        textNode = Document.createTextNode(text)
        elementNode.appendChild(textNode)
        return elementNode
